package com.demo;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

public class DependencyResolver {
    private static final Map<Class<?>, Object> INSTANCE_CACHE = new HashMap<>();

    public static <T> T getInstance(Class<T> clazz) throws Exception {
        if (INSTANCE_CACHE.containsKey(clazz)) {
            return (T) INSTANCE_CACHE.get(clazz);
        }

        // 1. 预创建半成品对象
        T instance = (T) clazz.getDeclaredConstructor().newInstance();
        INSTANCE_CACHE.put(clazz, instance);

        // 2. 获取有参构造器并注入依赖
        Constructor<?> constructor = clazz.getDeclaredConstructors()[0];
        Class<?>[] paramTypes = constructor.getParameterTypes();
        Object[] params = new Object[paramTypes.length];
        
        for (int i = 0; i < paramTypes.length; i++) {
            params[i] = getInstance(paramTypes[i]);  // 递归解决依赖
        }

        // 3. 重新构造完整对象
        instance = (T) constructor.newInstance(params);
        INSTANCE_CACHE.put(clazz, instance);  // 更新缓存

        return instance;
    }
}